<template>
    <basic-container>

      <template>
        <div class="form-designer">
          <el-container>
        <!--    <el-aside width="20%">
              <el-header style="height:40px;text-align: center;line-height: 40px">工序</el-header>
              <el-button v-for="process in pfocProcessList" @click="addProcessNode(process.processName,process.id)" style="margin: 5px 5px;min-width:45%" >{{process.processName}}</el-button>
            </el-aside>-->
            <el-main>
                <div style="height: auto;border-left: 1px solid #e0e0e0;line-height: 50px;padding-left:5px ">
                  产品类型:<el-select v-model="productLineType" placeholder="请选择产品类型"  disabled filterable clearable style="width:200px;margin-right: 5px">
                  <el-option
                    v-for="item in productLineTypeList"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                  品号：<!--<avue-input v-model="articleNumber" style="width:140px;margin-right: 5px" placeholder="请输入品号" ></avue-input>-->
                  <avue-select   v-model="articleNumber" filterable  clearable multiple  dialogWidth="100%"  style="width:200px;margin-right: 5px"
                                  placeholder="请选择品号"  :props="{label: 'label',value: 'value'}"
                                 :dic="articleNumbeList" ></avue-select>
                  <!--工艺产线名称:<avue-input v-model="craftLineName" style="width:180px;margin-right: 5px" placeholder="请输入工艺产线名称" ></avue-input>-->

                  工艺模板:<el-select v-model="craftLineName" placeholder="请选择工艺模板"  filterable clearable style="width:200px;margin-right: 5px">
                            <el-option
                              @click.native="craftLineChange(item)"
                              v-for="item in craftProductList"
                              :key="item.id"
                              :label="item.craftLineName"
                              :value="item.id">
                            </el-option>
                          </el-select>
                  <el-button type="primary" @click="saveLine">保存</el-button>
        <!--          <el-button type="primary"
                             @click="handleNext">下一个节点</el-button>

                  <el-button type="primary"
                             @click="viewShunxu">查看节点顺序</el-button>-->
                </div>
                <avue-flow :height="800"
                                  width="100%"
                                  ref="flow"
                                  :option="option"
                                  v-model="flowForm">
                <template #header="{node}" >
                  {{(node || {}).name}}
                  <i class="el-icon-delete"  style="float: right;line-height: 30px;margin-right: 2px" @click="deleteNode(node.id)"></i>
                </template>
                <template slot-scope="{node}">
                  <el-descriptions  class="margin-top"  title="工序属性" :column="1" size="small" border >
                    <el-descriptions-item v-for="attr in processAttributeList" :label="attr.attributeName">
                      <avue-select   v-model="form[node.id+`_`+attr.attributeField]"  multiple v-if="attr.attributeName!='设备' && attr.attributeName!='工具'&& attr.attributeName!='夹具'" filterable clearable  dialogWidth="100%"  :placeholder="`请选择`+attr.attributeName"  :props="{label: 'label',value: 'value'}"  :dic=" processAttributeDataList[attr.attributeField]" ></avue-select>
                    </el-descriptions-item>
                    <el-descriptions-item label="设备分类">
                      <avue-select   v-model="form[node.id+`_deviceClass`]" filterable clearable  dialogWidth="100%"  multiple placeholder="请选择设备分类"  :props="{label: 'label',value: 'value'}"  :dic="deviceClassList" ></avue-select>
                    </el-descriptions-item>
                  </el-descriptions>
                </template>
              </avue-flow>

            </el-main>
          </el-container>
        </div>
      </template>


      <template>
      </template>
    </basic-container>
</template>

<script>
    import { getProcessAttributeList,getProcessAttributeDataList,getDeviceClassList} from '@/api/pfoc/processattribute'
    import {getPfocProcessList } from '@/api/pfoc/pfocprocess'
    import {saveCraftProdictLine } from '@/api/pfoc/craftproductline'
    import {getCraftProductList } from '@/api/pfoc/craftproduct'
    import { getItemCodeList } from '@/api/workorder/workordercps'  //获取品号集合


    export default {
        name: "craft",
        props:{
            productLineTypeList:{//产线类型集合
                type:Array
            }
        },
        data() {
            return {
                count: 0,
                nodeCount:0,//节点下标
                form: [],//提交时数据集合
                flowForm:'',
                pfocProcessList:[],//工序集合
                craftProductList:[],//工艺产线集合
                processAttributeList:[],//工序通用属性集合
                processAttributeDataList:[],//工序通用属性数据集合
                deviceClassList:[],//设备分类集合
                articleNumber:null,//品号
                craftLineName:null,//工艺产线名称
                productLineType:null,//产线类型
                option: {
                    name: null,
                    nodeList: [],//工序节点集合
                    lineList: [],//工序各节点指向顺序集合
                },
                articleNumbeList:[],//品号集合
            };
        },
        created() {
            //获取品号集合
            this.getItemCodeListData();
        },
        computed: {
            nodeList () {
                return this.option.nodeList
            }

        },
        mounted() {
            this.nodeCount = this.option.nodeList.length;//初始化节点下标
            //获取工序
            // this.getPfocProcessListData();
            //获取工艺产线集合
            this.getCraftProductListData();
            //获取通用工序属性
            this.getProcessAttributeListData();
            //获取通用工序属性数据
            this.getProcessAttributeDataListData();
            //获取设备分类数据
            this.getDeviceClassListData();

        },
        methods: {
            //工艺产线选择
            craftLineChange(row){
                 this.$refs.flow.resetPlumb();//清空画布
                for(var i= this.option.nodeList.length-1;i>=0;i--){
                     var id  =this.option.nodeList[i].id;
                     //动态节点变量删除
                     for (var j = 0; j < this.processAttributeList.length; j++) {
                         this.$delete(this.form, id + "_" + this.processAttributeList[j].attributeField)
                     }
                     this.$delete(this.form, id+"_deviceClass");
                }

                //获取工艺产线主表数据
                this.craftLineMainData= row;//工艺产线主变数据
                //获取工艺产线子表数据
                // this.articleNumber=this.craftLineMainData.articleNumber;//品号
                this.craftLineName=this.craftLineMainData.craftLineName;//工艺产线名称
                this.productLineType=this.craftLineMainData.productLineType;//产线类型
                //设置反显工序
                this.option.nodeList = JSON.parse(this.craftLineMainData.processNodes);
                //设置反显工序指向顺序
                this.option.lineList =  JSON.parse(this.craftLineMainData.processNodeLine);
                //初始化节点下标
                var n =  this.option.nodeList[ this.option.nodeList.length-1].id;
                this.nodeCount = parseInt(n.split("node")[1])+1;
                //重新初始化flow组件
                this.$refs.flow.init();
                console.log(this.form)
                console.log(this.option.nodeList)

            },
            /**获取品号*/
            getItemCodeListData(){
              getItemCodeList().then(response => {
                    this.articleNumbeList=response.data.data;
                })
            },
            /**获取工序*/
            getPfocProcessListData(){
                getPfocProcessList().then(response => {
                    this.pfocProcessList=response.data.data;
                    // console.log(this.pfocProcessList)
                })

            },
            /**获取工艺产线集合*/
            getCraftProductListData(){
                getCraftProductList().then(response => {
                    this.craftProductList=response.data.data;
                    // console.log(this.pfocProcessList)
                })

            },
            /**获取通用工序属性*/
            getProcessAttributeListData(){
                getProcessAttributeList().then(response => {
                    this.processAttributeList=response.data.data;
                    // console.log(this.processAttributeList)
                })

            },
            /**获取通用工序属性数据*/
            getProcessAttributeDataListData(){
                getProcessAttributeDataList().then(response => {
                    this.processAttributeDataList=response.data.data;
                    // console.log(this.processAttributeDataList)
                })
            },
            /**获取设备分类数据*/
            getDeviceClassListData(){
                getDeviceClassList().then(response => {
                    this.deviceClassList=response.data.data;
                    // console.log(this.deviceClassList)
                })
            },
            /**添加工序*/
            addProcessNode(name,id,workshopSection){//工序名称，工序ID
                this.$refs.flow.addNode(name,id,this.nodeCount);//添加节点
                //注册动态节点变量
                for(var i=0;i<this.processAttributeList.length;i++){
                    this.$set(this.form, "node"+this.nodeCount+"_"+this.processAttributeList[i].attributeField, null);
                }
                this.$set(this.form, "node"+this.nodeCount+"_processName", name);//注册动态节点-当前工序名称
                this.$set(this.form, "node"+this.nodeCount+"_processId", id);//注册动态节点-当前工序ID
                this.nodeCount=this.nodeCount+1;//更新节点下标
                console.log(this.form)
                console.log(this.option.nodeList)
            },
            /**删除工序*/
            deleteNode(id){
                var t = this;
                 this.$confirm("确定要删除节点" + id + "?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                    closeOnClickModal: !1
                }).then((function() {
                     t.$refs.flow.deleteNode(id);
                     t.option.nodeList = t.option.nodeList;
                     //动态节点变量删除
                     for (var i = 0; i < t.processAttributeList.length; i++) {
                         t.$delete(t.form, id + "_" + t.processAttributeList[i].attributeField)
                     }
                    // t.$delete(t.form, id+ "_processName");//删除动态节点-当前工序名称
                  //   t.$delete(t.form, id + "_processId");//删除动态节点-当前工序ID
                     t.$delete(t.form, id+"_deviceClass");
                     console.log(t.form)
                     console.log(t.option.nodeList)
                })).catch((function() {}))
            },
            /**保存工艺产线*/
            saveLine(){
                if(this.validatenull(this.articleNumber)){
                    this.$message.warning("品号不能为空。")
                    return;
                }
                if(this.validatenull(this.craftLineName)){
                    this.$message.warning("工艺产线名称不能为空。")
                    return;
                }
                if(this.validatenull(this.option.nodeList)){
                    this.$message.warning("请选择工序创建工艺产线。")
                    return;
                }
              //组装需要提交的数据-工艺主表数据组装
                var params = {};//主表参数集合
                params.articleNumber = this.articleNumber;//品号
                params.craftLineName = this.craftLineName;//工艺产线名称
                params.productLineType = this.productLineType;//产线类型名称
                params.processNodes = JSON.stringify(this.option.nodeList);//工序节点集合（其中mark字段为工序ID）
                params.processNodeLine = JSON.stringify(this.option.lineList);//工序各节点指向顺序集合
                console.log(params)

               //组装需要提交的数据-工艺子表数据组装
                var objArr = [];
                //循环工序节点集合
                for(var i=0;i<this.option.nodeList.length;i++){
                    var obj = new Object();//创建对象
                    //循环工序属性取出每个工序的个属性数据加入到对象
                    for(var j=0;j<this.processAttributeList.length;j++){
                        //将工序属性集合中的属性加入对象同时取出form集合中对应的属性数据放入属性对象中
                        if(!this.validatenull(this.form[this.option.nodeList[i].id+'_'+this.processAttributeList[j].attributeField])) {
                            obj[this.processAttributeList[j].attributeField] = this.form[this.option.nodeList[i].id + '_' + this.processAttributeList[j].attributeField].toString();
                        }else{
                            obj[this.processAttributeList[j].attributeField] =null;
                        }
                    }
                    if(!this.validatenull(this.form[this.option.nodeList[i].id + '_deviceClass'])) {
                        obj['deviceClass'] = this.form[this.option.nodeList[i].id + '_deviceClass'].toString();
                    }else{
                        obj['deviceClass'] = null;
                    }
                    obj['processId'] = this.option.nodeList[i].mark;//取出工序ID加入对象
                    obj['nodeId'] = this.option.nodeList[i].id;
                    //最后加入提交数据数组
                    objArr.push(obj)
                }
                console.log(objArr)
                var data={
                    craftProductLine:params,
                    craftProductLineDetailsList:objArr
                }
                //提交
                saveCraftProdictLine(data).then(response => {
                    this.$message.success("保存成功。")
                    this.$emit('closeAddCraft');//关闭新增页面
                    this.tableLoading = false
                }).catch(() => {
                    this.tableLoading = false
                });
            },
            handleClick (node) {
                this.$message.success(JSON.stringify(node))
            },
            handleNext () {
                this.count++
                if (this.count >= this.nodeList.length) {
                    this.count = 0;
                }
                this.flowForm = this.nodeList[this.count].id;
            },
            viewShunxu(){
                this.$message.success(JSON.stringify(this.option.lineList))
                /*this.$message.success(JSON.stringify(this.option.nodeList))*/
            },
        }
    };
</script>

<style scoped>
  /deep/.avue-flow__node{
    height: auto!important;
  }
  /deep/ .avue-flow__node-header {
    line-height: 30px;
  }
  /deep/.el-descriptions__title {
    font-size: 14px;
    font-weight: 400;
    margin-top: 5px;
  }
</style>
